package cn.cjj.gulimall.auth.web;


import cn.cjj.common.constant.AuthServerConstant;
import cn.cjj.common.utils.R;
import cn.cjj.common.vo.MemberResponseVo;
import cn.cjj.gulimall.auth.feign.MemberFeignService;
import cn.cjj.gulimall.auth.vo.SocialUser;
import com.alibaba.fastjson.JSON;
import com.ejlchina.http.HTTP;
import com.ejlchina.http.HttpResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;

/**
 * @author CuiJunJie
 * @create 2021/7/5-15:14
 */
@Controller
public class OAuth2Controller {

    @Autowired
    MemberFeignService memberFeignService;


    @RequestMapping("/oauth2.0/weibo/success")
    public String weibo(@RequestParam("code") String code, HttpSession session) {
        HTTP http = HTTP.builder()
                .baseUrl("https://api.weibo.com")
                .build();
        HttpResult httpResult = http.sync("/oauth2/access_token")
                .addBodyParam("client_id", "3825865537")
                .addBodyParam("client_secret", "f729e774474c47154f439a352fdce2a5")
                .addBodyParam("grant_type", "authorization_code")
                .addBodyParam("code", code)
                .addBodyParam("redirect_uri", "http://auth.gulimall.com/oauth2.0/weibo/success")
                .post();

        if (httpResult.getState() == HttpResult.State.RESPONSED) {
            HttpResult.Body body = httpResult.getBody().cache();
            System.out.println(body);

            SocialUser socialUser = body.toBean(SocialUser.class);
            System.out.println(socialUser);

            R r = memberFeignService.oauthLogin(socialUser);
            Object data = r.get("data");
            String memberJsonString = JSON.toJSONString(data);
            MemberResponseVo member = JSON.parseObject(memberJsonString, MemberResponseVo.class);
            session.setAttribute(AuthServerConstant.LOGIN_USER, member);
        } else {
            return "redirect:http://auth.gulimall.com/login.html";
        }

        return "redirect:http://gulimall.com";
    }
}
